/**
 * iMap V2.0
 * Copyright (c) 2017  by BEN
 * Created Date： 2016/5/1
 * Update Date: 2017/7/6
 */

/**
 * OL地图调用插件封装
 * 例子：$('#map').iMap( @options )
 * @options {{
 *      mapUrl: String,		'resources/upload/map/map.png'	//地图URL
 *      extent: Array		[0, -2000, 6817, 0],             //地图边界(px)			[left, bottom, right, top]
 *      mapSize: Array		[68.4, 19.11],                  //地图实际尺寸(m)		[α长,α宽]
 *      imageSize: Array	[6817, 2010],                   //图片尺寸(px)			[β长,β宽]
 *      minZoom: Number,    1                               //地图最小缩放比例		建议：1
 *      maxZoom: Number,    6                               //地图最大缩放比例		建议：6
 *      zoom: Number,       2                               //当前地图缩放等级		建议：2
 *      dPR: Number,                            			//像素比(devicePixelRatio)		β长/α长
 *      MapClick: Boolean,							 		//地图Click事件			默认true
 *      MapPointerMove:Boolean								//地图Move事件			默认true
 *      controls: *[]                                       //工具栏设置(暂无)
 * }}
 *
 */

// import ol from 'openlayers'
// let ol = this.$ol
import Map from 'ol/Map.js'
// import PluggableMap from 'ol/PluggableMap'

import View from 'ol/View.js'
import Overlay from 'ol/Overlay.js'
import {
  loadType,
  FenceAjaxLayerId
} from '@/api/cy.js'
import {
  Tile as TileLayer,
  Vector as VectorLayer,
  Image
} from 'ol/layer.js'
// import {OSM, Vector as VectorSource, ImageStatic} from 'ol/source.js'
import {
  OSM,
  Vector,
  ImageStatic
} from 'ol/source.js'

import {
  Circle,
  Fill,
  Stroke,
  Style,
  Text,
  Icon,
  Circle as CircleStyle
} from 'ol/style.js'
import {
  FullScreen,
  ScaleLine,
  defaults,
  Rotate
} from 'ol/control.js'
import {
  Projection
} from 'ol/proj.js'
import Feature from 'ol/Feature'
import {
  GeoJSON
} from 'ol/format.js'
import ImageLayer from 'ol/layer/Image'
import Static from 'ol/source/ImageStatic'
import {
  Draw,
  Modify,
  Snap,
  Select,
  Translate,
  Interaction,
  defaults as defaultInteractions,
  DragRotateAndZoom
} from 'ol/interaction.js'
import {
  cameraServerUrl
} from './global'
import {
  icon
} from 'leaflet'
import {
  baseUrl
} from './global'
// import i18n from '../../i18n/i18n'

import Cookie from 'js-cookie'
import {
  Circle as CircleFeature
} from 'ol/geom'

import {
  easeOut
} from 'ol/easing'
import {
  unByKey
} from 'ol/Observable'
import {
  getCenter
} from 'ol/extent'
// import {  } from 'ol/render'

let _this = null // 用来存储Vue实例this
let _cameraPreview = null

var _iMap;
var _dPR;
var OverlayLayer = null
var c
var TagLayer;
var AnchorLayer;
var VideoLayer;
var FenceLayer = null
var FenceSource = null
var CameraLayer = null
var CameraSource = null
var AlertorLayer = null
var AlertorSource = null
var TooltipElement, Tooltip
var measureTooltipElement, measureTooltip
var _VideoIndex = 0

var _View, _Project

var mapZoom = 2 // 记录地图的缩放级别
var _zero

var _View

var tagTypes = {}

// 传递this对象
const sendThis = (vm) => {
  _this = vm
}

// 传递摄像头预览窗口
const sendCameraPreview = (vm) => {
  _cameraPreview = vm
};

(function ($) {
  $.fn.iMap = function (options) {
    $(this).empty() // 清除、重置map内容
    var _opts = $.extend({}, $.fn.iMap.defaults, options)
    // console.log('地图',_opts, _opts.extent)
    _dPR = _opts.dPR // 获取像素比
    var _Target = $(this).attr('id')
    _Project = new Projection({
      code: 'EPSG:900931', // 用“米”做单位的x/y坐标的投影
      units: 'pixels', // 单位：像素
      extent: _opts.extent
    })
    var _Controls = new defaults().extend([ // 控制工具栏
      // new FullScreen(), // 添加全屏按钮
    ])

    var _Layers = ([
      new ImageLayer({
        source: new Static({
          // attributions: "&copy; <a  href='http://www.woxuwireless.com' target='_blank'>woxuwireless.com</a>", //添加版权内容
          imageSize: _opts.imageSize, // 图片尺寸（px）  [长,宽]
          url: _opts.mapUrl, // 地图URL
          projection: _Project,
          imageExtent: _opts.extent
        })
      })

    ])

    _View = new View({ // 地图显示配置
      projection: _Project,
      // zoom: _opts.zoom,
      zoom: 2,
      maxZoom: 8,
      // minZoom: _opts.minZoom,
      // maxZoom: _opts.maxZoom,
      center: getCenter(_opts.extent)
    })

    // 将地图显示的中心点设置为坐标原点
    // const centerpos = _TransPixel([0, 0])
    // 地图初始化时，将零点显示在正中间
    // _View.setCenter(centerpos)

    /** *_iMap地图事件*/
    _iMap = new Map({ // 方法：_iMap
      interactions: defaultInteractions().extend([
        new DragRotateAndZoom()
      ]),
      controls: _Controls,
      layers: _Layers,
      target: _Target, // 地图目标层ID
      view: _View,
      renderer: 'canvas'
    })

    // ***********************debug cao
    // _iMap.addControl(new FullScreen())

    // //***********************debug cao
    /** 加载地图事件（Click、PointerMove）*/
    if (_opts.MapClick) {
      _iMap.on('click', MapClick) // 监听点击事件
    }
    if (_opts.MapPointerMove) {
      _iMap.on('pointermove', MapPointerMove) // 监听鼠标移动事件
    }
    if (_opts.MapZoom) {
      _View.on('change:resolution', checkZoom) // 监听地图缩放事件
    }
    checkZoom()
  }
})(jQuery)

function removeMap() {
  _iMap = null
}

/**
 * 事件扩展
 * 调用：$.Load.Map( @param )
 */

/** 加载地图*/
function Load_Map(url, RealWidth, RealHeight, PixelWidth, PixelHeight, dPR, ZeroPoint) {
  _dPR = dPR
  _zero = _TransPixel(ZeroPoint)
  var left = _zero[0]
  var bottom = _zero[1] + (-PixelHeight)
  var right = _zero[0] + PixelWidth
  var top = _zero[1]
  $('#map').iMap({
    mapUrl: url, // 地图URL
    extent: [left, bottom, right, top], // [left, bottom, right, top]
    mapSize: [RealWidth, RealHeight], // 地图实际尺寸（m）  [长,宽]
    imageSize: [PixelWidth, PixelHeight], // 图片尺寸（px）  [长,宽]
    minZoom: 0, // 地图最小缩放比例，建议(1)
    maxZoom: 8, // 地图最大缩放比例，建议(6~8)
    zoom: 2, // 当前地图缩放等级
    dPR: dPR, // 像素比initialize
    MapClick: true, // 地图Click事件，默认true
    MapPointerMove: true, // 地图Move事件，默认true
    MapZoom: true // 监听地图缩放级别时间
  })
  // _View.setCenter([-(1377 / 2), -(772 / 2)])
}

/**
 * 振波动画
 */
function flashAnimate(feature) {
  const start = new Date().getTime()
  const listenerKey = _iMap.on('postcompose', animate)
  // let listenerKey = _iMap.on('postrender', animate);

  function animate(event) {
    const vectorContext = event.vectorContext
    // let vectorContext = getVectorContext(event);

    const frameState = event.frameState
    const flashGeom = feature.getGeometry().clone()

    const elapsed = frameState.time - start
    const elapsedRatio = elapsed / 1200

    const radius = easeOut(elapsedRatio) * 25 + 5
    const opacity = easeOut(1 - elapsedRatio)

    const style = new Style({
      image: new CircleStyle({
        radius: radius,
        stroke: new Stroke({
          color: 'rgba(255, 0, 0, ' + opacity + ')',
          width: 0.25 + opacity
        })
      })
    })

    vectorContext.setStyle(style)
    vectorContext.drawGeometry(flashGeom)

    if (elapsed > 1000) {
      unByKey(listenerKey)
      return
    }
    // 合成动画
    _iMap.render()
  }
}
/**
 * 获取目前所有数据类型
 */

function LoadTypeData() {
  loadType().then(res => {
    if (res.code == 200) {
      const datas = res.data
      for (let i = 0; i < datas.length; i++) {
        const type = datas[i].type
        if (tagTypes[type]) {
          tagTypes[type].push(datas[i])
        } else {
          tagTypes[type] = []
          tagTypes[type].push(datas[i])
        }
      }
    }
  })
}
// function LoadTypeData () {
//   tagTypes = [];

//   let url = baseUrl + "/resourceType/findList";

//   $.ajax({
//     url: url,
//     type: "get",
//     dataType: "json",
//     headers: {
//       "token": Cookie.get("token")
//     },
//     success: function (data) {
//       if (data.code === 200) {
//         // 按大类进行分类整理
//         let datas = data.data;
//         for (let i = 0; i < datas.length; i++) {
//           let type = datas[i].type;
//           if (tagTypes[type]) {
//             tagTypes[type].push(datas[i]);
//           } else {
//             tagTypes[type] = [];
//             tagTypes[type].push(datas[i]);
//           }
//         }

//       } else if (data.code === 707) {
//         _this.Error707();
//       }
//     }
//   });
// }

function getTypeData() {
  return tagTypes
}

/** 加载标签*/
function Load_Tag(Geo, Ref) {
  var _interval
  clearInterval(_interval)
  var TagSource = new Vector({
    wrapX: false
  })
  TagLayer = new VectorLayer({
    minResolution: 0,
    maxResolution: _dPR * 3.6,
    source: TagSource,
    zIndex: 10000,
    renderBuffer: 100,
    updateWhileAnimating: true,
    updateWhileInteracting: true,
    style: function (feature, resolution) {
      return $.TagStyle(feature, resolution, -9999)
    }
  })
  _iMap.addLayer(TagLayer)
  TagAjax(Geo, TagSource)
}

/** 加载基站*/
function Load_Anchor(Geo, Ref) {
  var _interval
  clearInterval(_interval)
  var AnchorSource = new Vector({
    url: Geo,
    format: new GeoJSON()
  })
  AnchorLayer = new VectorLayer({
    minResolution: 0,
    maxResolution: _dPR * 1.2,
    source: AnchorSource,
    zIndex: 9000,
    style: function (feature, resolution) {
      return $.AnchorStyle(feature, resolution)
    }
  })
  _iMap.addLayer(AnchorLayer)
  $.AnchorAjax(Geo, AnchorSource)
}

// 释放围栏容器
function releaseFence() {
  if (FenceSource != null) {
    const old = FenceSource.getFeatures()
    let len = old.length
    while (len > 0) {
      len--
      FenceSource.removeFeature(old[len])
      old.splice(len, 1)
    }
  }

  if (FenceLayer != null) {
    _iMap.removeLayer(FenceLayer)
  }

  FenceSource = null
  FenceLayer = null
}

/**
 * 清除地图中的围栏
 */
function clearFence() {
  if (FenceSource != null) {
    const old = FenceSource.getFeatures() // 现在已有的标签数据
    let len = old.length
    while (len > 0) {
      len--
      FenceSource.removeFeature(old[len])
      old.splice(len, 1)
    }
  }
}

/** 加载围栏*/
function Load_Fence(Geo) {
  // if (FenceSource === null) {
  //   FenceSource = new Vector({
  //     wrapX: false
  //   })
  // } else
  if (FenceSource != null) {
    _iMap.removeLayer(FenceLayer)
    FenceSource = null
    FenceLayer = null
  }
  FenceSource = new Vector({
    wrapX: false
  })
  if (FenceLayer === null) {
    FenceLayer = new VectorLayer({
      minResolution: 0,
      // maxResolution: _dPR * 3.6,
      maxResolution: _dPR * 1.2,
      source: FenceSource,
      // zIndex: 8000,
      style: function (feature, resolution) {
        const fenceType = feature.get('fencetype')
        if (feature.get('id') == undefined) {
          return FenceStyle(feature, '255, 0, 0')
        }
        if (!(typeof fenceType === 'undefined')) {
          const arr = fenceType.split(',')
          if (arr.length > 1) {
            return FenceStyle(feature, '165,42,42')
          }
        }

        // 根据不同的围栏类型，显示不同的颜色
        if (fenceType == 'camera') {
          return FenceStyle(feature, '0, 153, 102')
        } else if (fenceType == 'operation') {
          return FenceStyle(feature, '0,153,204')
        } else if (fenceType == 'alarm') {
          return FenceStyle(feature, '255,0,0')
        } else if (fenceType == 'check') {
          return FenceStyle(feature, '255,255,0')
        } else if (fenceType == 'polling') {
          return FenceStyle(feature, '255,165,0')
        } else {
          return FenceStyle(feature, '160,32,240')
        }
      }
    })
    _iMap.addLayer(FenceLayer)
  }

  if (Geo != '') {
    FenceAjax(Geo, FenceSource)
  }
}

function Load_MapFence(Geo) {
  if (FenceSource === null) {
    FenceSource = new Vector({
      wrapX: false
    })
  }

  if (FenceLayer === null) {
    FenceLayer = new VectorLayer({
      minResolution: 0,
      maxResolution: _dPR * 1.2,
      source: FenceSource,
      zIndex: 8000,
      style: function (feature, resolution) {
        const fenceType = feature.get('fencetype')

        if (!(typeof fenceType === 'undefined')) {
          const arr = fenceType.split(',')
          if (arr.length > 1) {
            return MapFenceStyle(feature, '165,42,42')
          }
        }

        if (fenceType == 'camera') {
          return MapFenceStyle(feature, '0, 153, 102')
        } else if (fenceType == 'operation') {
          return MapFenceStyle(feature, '0,153,204')
        } else if (fenceType == 'alarm') {
          return MapFenceStyle(feature, '255,0,0')
        } else if (fenceType == 'check') {
          return MapFenceStyle(feature, '255,255,0')
        } else if (fenceType == 'polling') {
          return MapFenceStyle(feature, '255,165,0')
        } else {
          return MapFenceStyle(feature, '160,32,240')
        }
      }
    })
    _iMap.addLayer(FenceLayer)
  }

  if (Geo != '') {
    FenceAjax(Geo, FenceSource)
  }
}

// 加载本地围栏
function loadLocalFence(fenceGeo, id) {
  if (FenceSource === null) {
    FenceSource = new Vector({
      wrapX: false
    })
  }

  if (FenceLayer === null) {
    FenceLayer = new VectorLayer({
      minResolution: 0,
      maxResolution: _dPR * 1.2,
      source: FenceSource,
      zIndex: 8000,
      style: function (feature, resolution) {
        const fenceType = feature.get('fencetype')
        if (!(typeof fenceType === 'undefined')) {
          const arr = fenceType.split(',')
          if (arr.length > 1) {
            return FenceStyle(feature, '165,42,42')
          }
        }

        if (fenceType == 'camera') {
          return FenceStyle(feature, '0, 153, 102')
        } else if (fenceType == 'operation') {
          return FenceStyle(feature, '0,153,204')
        } else if (fenceType == 'alarm') {
          return FenceStyle(feature, '255,0,0')
        } else if (fenceType == 'check') {
          return FenceStyle(feature, '255,255,0')
        } else if (fenceType == 'polling') {
          return FenceStyle(feature, '255,165,0')
        } else {
          return FenceStyle(feature, '160,32,240')
        }
        /* return FenceStyle(feature, '#111')*/
      }
    })
    _iMap.addLayer(FenceLayer)
  }
  var format = new GeoJSON()

  const newFeatures = format.readFeatures(fenceGeo)
  newFeatures.forEach(function (f) {
    const coord = f.getGeometry().getCoordinates()
    f.getGeometry().setCoordinates(_TransPixel(coord))
    f.setId(id)
    FenceSource.addFeature(f)
  })
}

// 根据围栏ID清除地图中的围栏
function deleteFence(id) {
  if (FenceSource !== null) {
    const fence = FenceSource.getFeatureById(id)
    if (fence) {
      FenceSource.removeFeature(fence)
    }
  }
}

/** 加载摄像头*/
function Load_Camera(Geo) {
  CameraSource = new Vector({
    wrapX: false
  })
  CameraLayer = new VectorLayer({
    minResolution: 0,
    maxResolution: _dPR * 1.2,
    source: CameraSource,
    zIndex: 8000,
    style: function (feature, resolution) {
      return CameraStyle(feature, resolution)
    }
  })
  _iMap.addLayer(CameraLayer)
  CameraAjax(Geo, CameraSource)
}

function CameraAjax(Geo, source) {
  $.ajax({
    url: Geo,
    type: 'get',
    dataType: 'json',
    headers: {
      'token': Cookie.get('token')
    },
    success: function (data) {
      if (data.code === 200) {
        var format = new GeoJSON()
        var newFeatures = format.readFeatures(data.data)
        newFeatures.forEach(function (f) {
          var coord = f.getGeometry().getCoordinates()
          f.getGeometry().setCoordinates(_TransPixel(coord))
          f.setId(f.get('idx'))
          source.addFeature(f)
        })
      } else if (data.code === 707) {
        _this.Error707()
      }
    },
    error: function (err) {
      console.log('err', err)
    }
  })
}

/**
 *标签--样式设置
 */
function CameraStyle(f, r) {
  return [
    new Style({
      image: new Icon({
        anchorXUnits: 'fraction',
        anchorYUnits: 'fraction',
        offset: [0, 0],
        Size: [f.get('size'), f.get('size')],
        src: '../../../static/img/icon/camera.png',
        color: '#409EFF',
        opacity: 1
      }),
      text: new Text({
        text: f.get('cameraName'),
        font: '10px Arial',
        textAlign: 'center',
        textBaseline: 'middle',
        offsetX: 0,
        offsetY: 30 * 2 / 3,
        fill: new Fill({
          color: '#fff'
        }),
        stroke: new Stroke({
          color: '#000',
          width: 3
        })
      })
    })
  ]
}
/** ************************************************/
/** 加载摄像头*/
function Load_Alertor(Geo) {
  AlertorSource = new Vector({
    wrapX: false
  })
  AlertorLayer = new VectorLayer({
    minResolution: 0,
    maxResolution: _dPR * 1.2,
    source: AlertorSource,
    zIndex: 8000,
    style: function (feature, resolution) {
      return AlertorStyle(feature, resolution)
    }
  })
  _iMap.addLayer(AlertorLayer)
  AlertorAjax(Geo, AlertorSource)
}

function AlertorAjax(Geo, source) {
  $.ajax({
    url: Geo,
    type: 'get',
    dataType: 'json',
    headers: {
      'token': Cookie.get('token')
    },
    success: function (data) {
      if (data.code === 200) {
        var format = new GeoJSON()
        var newFeatures = format.readFeatures(data.data)
        newFeatures.forEach(function (f) {
          var coord = f.getGeometry().getCoordinates()
          f.getGeometry().setCoordinates(_TransPixel(coord))
          f.setId(f.get('idx'))
          source.addFeature(f)
        })
      } else if (data.code === 707) {
        _this.Error707()
      }
    },
    error: function (err) {
      console.log('err', err)
    }
  })
}

/**
 *标签--样式设置
 */
function AlertorStyle(f, r) {
  return [
    new Style({
      image: new Icon({
        anchorXUnits: 'fraction',
        anchorYUnits: 'fraction',
        offset: [0, 0],
        Size: [f.get('size'), f.get('size')],
        src: '../../../static/img/icon/alertor.png',
        color: '#FF0000',
        opacity: 1
      }),
      text: new Text({
        text: f.get('name'),
        font: '10px Arial',
        textAlign: 'center',
        textBaseline: 'middle',
        offsetX: 0,
        offsetY: 30 * 2 / 3,
        fill: new Fill({
          color: '#fff'
        }),
        stroke: new Stroke({
          color: '#000',
          width: 3
        })
      })
    })
  ]
}
/** ************************************************/

/**
 * AJAX获取标签GeoJson数据
 */
function TagAjax(Geo, source) {
  const self = this
  $.ajax({
    url: Geo,
    type: 'get',
    dataType: 'json',
    headers: {
      'token': Cookie.get('token')
    },
    success: function (data) {
      if (data.code === 200) {
        if (data.features == undefined) {
          return
        } else {
          var format = new GeoJSON()
          var Nfeatures = format.readFeatures(data)
          Nfeatures.forEach(function (f) {
            var Nid = f.get('id')
            var Ncoords = $._TransPixel(f.getGeometry().getCoordinates())
            f.getGeometry().setCoordinates(Ncoords)
            source.addFeature(f)
            // 如已打开气泡，同步更新气泡坐标
            var t = _iMap.getOverlayById(Nid)
            if (t != null) {
              if (t.getPosition() != undefined) {
                t.setPosition(Ncoords)
              }
            }
          })
        }
      } else if (data.code === 707) {
        _this.Error707()
      }
    }
  })
}

/**
 *标签--样式设置
 */
let b = -1

function TagStyle(f, r, x) {
  let temp = -9999
  let textname = ''
  let iconsrc = ''
  let iconcolor = ''
  // 判断是否是隧道版本
  if (x !== -9999) {
    const tempcoord = f.getGeometry().getCoordinates()
    const coords = _TransMetric(tempcoord, 2)
    temp = parseFloat(coords[0]).toFixed(2) - parseFloat(x).toFixed(2) - parseFloat(holeXCoordinateValue).toFixed(2)

    // textname = mapZoom >= 2 ? f.get('name') + '\n ' + i18n.t('realtime.tunnel.distanceToTheMouth') + temp.toFixed(2) + i18n.t('realtime.tunnel.holeUnit') : '';
  } else {
    textname = mapZoom >= 2 ? f.get('name') : ''
  }

  // 判断标签的类型及工种，用来显示不同的图标和颜色
  if (tagTypes[f.get('type')]) {
    const subtypes = tagTypes[f.get('type')]
    b = -1
    for (let i = 0; i < subtypes.length; i++) {
      if (subtypes[i].name === f.get('workTypeName')) {
        b = i
        break
      }
    }

    if (b != -1) { // 有这种类型的工种
      iconsrc = '../../../static/img/icon/' + subtypes[b].icon + '.png'
      iconcolor = subtypes[b].color
    } else {
      iconsrc = '../../../static/img/icon/5ren.png'
      iconcolor = '#409EFF'
    }
  } else {
    // 如果没有这种大类，使用默认图标
    iconsrc = '../../../static/img/icon/5ren.png'
    iconcolor = '#409EFF'
  }

  return [
    new Style({
      image: new Icon({
        anchorXUnits: 'fraction',
        anchorYUnits: 'fraction',
        offset: [0, 0],
        Size: [f.get('size'), f.get('size')],
        // src: f.get('icon'),
        src: iconsrc,
        color: iconcolor,
        opacity: 1
      }),

      text: new Text({
        // text: r < _dPR *1.2 ? f.get('name') : '',
        text: textname,
        font: '10px Arial',
        textAlign: 'center',
        textBaseline: 'middle',
        offsetX: 0,
        // offsetY: -f.get('size') * 2 / 3,
        offsetY: -f.get('size'),
        fill: new Fill({
          color: '#fff'
        }),
        stroke: new Stroke({
          color: '#000',
          width: 3
        })
      })
    })
  ]
}

/**
 *AJAX获取锚点GeoJson数据
 */
function AnchorAjax(Geo, source) {
  const self = this
  $.ajax({
    url: Geo,
    type: 'get',
    dataType: 'json',
    headers: {
      'token': Cookie.get('token')
    },
    success: function (data) {
      if (data.code === 200) {
        if (data.features == undefined) {
          return
        } else {
          var format = new GeoJSON()
          var features = format.readFeatures(data)
          features.forEach(function (f) {
            // var nid = f.get('id')
            var coords = $._TransPixel(f.getGeometry().getCoordinates())
            f.getGeometry().setCoordinates(coords)
            source.addFeature(f)
          })
        }
      } else if (data.code === 707) {
        _this.Error707()
      }
    }
  })
}

/**
 *锚点--样式设置
 */
function AnchorStyle(f, r) {
  return [
    new ol.style.Style({
      image: new Icon({
        anchorXUnits: 'fraction',
        anchorYUnits: 'fraction',
        offset: [0, 0],
        Size: [f.get('size'), f.get('size')],
        src: f.get('icon'),
        opacity: 1

      }),
      text: new Text({
        text: f.get('name'),
        font: 'bold 14px Arial',
        textAlign: 'center',
        textBaseline: 'middle',
        offsetX: 0,
        offsetY: f.get('size') * 2 / 3,
        fill: new Fill({
          color: '#333'
        }),
        stroke: new Stroke({
          color: '#fff',
          width: 3
        })
      })
    })
  ]
}

/**
 * AJAX获取电子围栏GeoJson数据
 */
function FenceAjax(Geo, source) {
  FenceAjaxLayerId(Geo).then(data => {
    if (data.code === 200) {
      if (data.data.length > 0) {
        var format = new GeoJSON()
        for (let i = 0; i < data.data.length; i++) {

          if (data.data[i].mark == undefined || data.data[i].mark == 'other') {
            var newFeatures = format.readFeatures(data.data[i])
            newFeatures.forEach(function (f) {
            
              // 去除“层”类型和“临时”类型围栏类型
              if (f.get('fencetype') != 'layer' && f.get('fencetype') != 'temporary') {
                var coord = f.getGeometry().getCoordinates()
                f.getGeometry().setCoordinates(_TransPixel(coord))
                f.setId(f.get('id'))
                source.addFeature(f)
              }
            })
          } else {
            const geometryData = data.data[i]
            const circleFeature = new Feature({
              geometry: new CircleFeature(_TransPixel(geometryData.geometry.coordinates[0][0]), _dPR * geometryData.geometry.coordinates[0][1])
            })
            circleFeature.setId(geometryData.id)
            circleFeature.properties = geometryData.properties
            circleFeature.coorRadiu = geometryData.geometry.coordinates[0][1]
            circleFeature.dotOrigin = geometryData.geometry.coordinates[0][0]
            circleFeature.set('name', geometryData.properties.name)
            circleFeature.set('fillColor', geometryData.properties.fillColor)
            circleFeature.set('frameColor', geometryData.properties.frameColor)
            circleFeature.set('id', geometryData.properties.id)
            circleFeature.set('type', geometryData.properties.type)
            circleFeature.set('layerId', geometryData.properties.layerId)
            circleFeature.set('fencetype',geometryData.properties.fencetype)
            source.addFeature(circleFeature)
          }



        }
      }
    } else if (data.code === 707) {
      _this.Error707()
    }
  })
}

// function FenceAjax (Geo, source) {
//   $.ajax({
//     url: Geo,
//     type: "GET",
//     dataType: "json",
//     headers: {
//       "token": Cookie.get("token")
//     },
//     success: function (data) {0707
//       if (data.code === 200) {
//         if (data.data.length > 0) {
//           var format = new GeoJSON();
//           for (let i = 0; i < data.data.length; i++) {
//             var newFeatures = format.readFeatures(data.data[i]);
//             newFeatures.forEach(function (f) {
//               // 去除“层”类型和“临时”类型围栏类型
//               if (f.get('fencetype') != "layer" && f.get('fencetype') != "temporary") {
//                 var coord = f.getGeometry().getCoordinates();
//                 f.getGeometry().setCoordinates(_TransPixel(coord));
//                 f.setId(f.get("id"));
//                 source.addFeature(f)
//               }
//             })
//           }
//         }
//       } else if (data.code === 707) {
//         _this.Error707();
//       }
//     }
//   })
// }

/**
 *电子围栏--样式设置
 */
function FenceStyle(f, r) {
  return [
    new Style({
      fill: new Fill({
        color: 'rgba(' + r + ',0.1)'
      }),
      stroke: new Stroke({
        lineDash: [1, 2, 3, 4, 5, 6],
        color: 'rgb(' + r + ')',
        width: 2
      }),
      image: new Circle({
        radius: 7,
        fill: new Fill({
          color: '#FF0000'
        })
      }),
      text: new Text({
        text: f.get('name'),
        font: 'bold 14px Arial',
        textAlign: 'center',
        textBaseline: 'middle',
        overflow: true,
        offsetX: 0,
        offsetY: 0,
        fill: new Fill({
          color: '#FF0000'
        }),
        stroke: new Stroke({
          color: '#fff',
          width: 3
        })
      })
    })
  ]
}

function MapFenceStyle(f, r) {
  return [
    new Style({
      fill: new Fill({
        color: 'rgba(' + r + ',0.3)'
      }),
      stroke: new Stroke({
        color: 'rgb(' + r + ',0.3)',
        width: 1
      }),
      image: new Circle({
        radius: 7,
        fill: new Fill({
          color: '#FF0000'
        })
      }),
      text: new Text({
        text: f.get('name'),
        font: 'bold 14px Arial',
        textAlign: 'center',
        textBaseline: 'middle',
        offsetX: 0,
        offsetY: 0,
        fill: new Fill({
          color: '#FF0000'
        }),
        stroke: new Stroke({
          color: '#fff',
          width: 3
        })
      })
    })
  ]
}
/**
 * AJAX获取视频GeoJson数据
 */
function VideoAjax(Geo, source) {
  const self = this
  $.ajax({
    url: Geo,
    type: 'get',
    dataType: 'json',
    headers: {
      'token': Cookie.get('token')
    },
    success: function (data) {
      if (data.code === 200) {
        if (data.features == undefined) {
          return
        } else {
          var format = new GeoJSON()
          var features = format.readFeatures(data)
          features.forEach(function (f) {
            var coords = $._TransPixel(f.getGeometry().getCoordinates())
            f.getGeometry().setCoordinates(coords)
            source.addFeature(f)
          })
        }
      } else if (data.code === 707) {
        _this.Error707()
      }
    }
  })
}

/**
 *电子围栏--样式设置
 */
function VideoStyle(f, r) {
  return [
    new Style({
      image: new Icon({
        anchorXUnits: 'fraction',
        anchorYUnits: 'fraction',
        offset: [0, 0],
        Size: [f.get('size'), f.get('size')],
        src: f.get('icon'),
        opacity: 1
      }),
      text: new Text({
        text: f.get('name'),
        font: 'bold 14px Arial',
        textAlign: 'center',
        textBaseline: 'middle',
        offsetX: 0,
        offsetY: -f.get('size') * 2 / 3,
        fill: new Fill({
          color: '#333'
        }),
        stroke: new Stroke({
          color: '#fff',
          width: 3
        })
      })
    })
  ]
}

/**
 *地图点击事件
 */
function MapClick(evt) {
  // 识别点击的位置有没有“对象”
  var feature = _iMap.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
    return feature
  })
  if (feature) {
    console.log(feature.get('type'))
    const type = feature.get('type')

    if (type == 'Video') {
      // //调用视频窗口事件
      if (window.top == window.self) {
        _ShowVideo(feature.getId())
      } else {
        window.parent.$._ShowVideo(feature.getId())
      }
    } else if (type === 'staff' || type === 'car' || type === 'material') {
      _Popup(feature, evt.coordinate) // 调用气泡
    } else if (type == 'Camera') {
      _PopupVideo(feature, evt.coordinate)
    } else if (type == 'Alertor') {
      // _PopupVideo(feature, evt.coordinate);
    }
  }
}

/**
 *地图Move事件
 */
function MapPointerMove(evt) {
  var element = $('.popup-info')
  if (evt.dragging) { // 如果是拖动地图造成的鼠标移动，则不作处理
    return
  }
  var hit = _iMap.hasFeatureAtPixel(evt.pixel)
  $(_iMap.getTargetElement()).css('cursor', hit ? 'pointer' : '')

  // 经过feature则显示当前id
  var feature = _iMap.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
    return feature
  })

  /** 隐藏机关 开始*/
  _createTooltip(true)
  Tooltip.setPosition(evt.coordinate)
  var coord = _TransMetric_XY(evt.coordinate, 2)

  $(TooltipElement).addClass('hidden')

  $('.positiondiv span').html(coord)
}

/**
 * 计算缩放级别
 */
function checkZoom() {
  mapZoom = _View.getZoom()
  calcScale(mapZoom)
}

function setMapCenter(center) {
  _View.setCenter(center)
}
/**
 * 计算比例尺
 */
function calcScale(zoom) {
  const res = _View.getResolution()
  const temp = (100 / _dPR) * res
  $('.scalediv span').html(temp.toFixed(2) + 'M')
}

/**
 * 加载视频窗口
 */
function _PopupVideo(f, pos) {
  // 先切换画面
  const element = document.getElementById('popup-video')
  const closer = $('#popup-video-closer')
  const popup = new Overlay({
    id: 'onlyCamera',
    element: element,
    positioning: 'center-center',
    offset: [0, 0],
    stopEvent: false,
    autoPan: true,
    autoPanAnimation: {
      duration: 250
    },
    position: pos
  })

  _iMap.addOverlay(popup)

  if (f) {
    closer.click(function () {
      popup.setPosition(undefined)
      this.blur()
      _this.$refs.video0.closePlayer()
    })
  } else {
    popup.setPosition(undefined)
  }
  _this.playUrl = 'ws://' + window.g.IP + ':8866/live?url=' + f.get('subStream')
  // _this.playUrl = 'ws://192.168.3.121:8866/live?url=' + f.get("subStream");
  _this.handlePlay()
}

/**
 * 加载气泡
 */
function _Popup(f, pos) {
  var element = document.getElementById('popup-info')
  var content = $('#popup-content')
  var closer = $('#popup-closer')

  var Popup = new Overlay({
    id: f.getId(),
    element: element,
    positioning: 'center-center',
    offset: [0, 0],
    stopEvent: false,
    autoPan: true,
    autoPanAnimation: {
      duration: 250
    },
    position: pos
  })
  _iMap.addOverlay(Popup)
  OverlayLayer = _iMap.getOverlayById(f.getId())
  if (f) {
    var C
    switch (f.get('type')) {
      case 'staff':
        C = '<li>名字：' + f.get('name') + '</li><li>工号：' + f.get('resourceId') + '</li><li>部门：' + f.get('deptname') + '</li><li>标签ID：' + f.get('tag_id') + '</li>'
        break
      case 'car':
        C = '<li>车辆：' + f.get('name') + '</li><li>车牌号：' + f.get('resourceId') + '</li><li>部门：' + f.get('deptname') + '</li><li>标签ID：' + f.get('tag_id') + '</li>'
        break
      case 'material':
        C = '<li>物料名称：' + f.get('name') + '</li><li>物料编号：' + f.get('resourceId') + '</li><li>部门：' + f.get('deptname') + '</li><li>标签ID：' + f.get('tag_id') + '</li>'
        break
      default:
        C = '<li>该类型资源不支持气泡</li>'
        break
    }
    content.html(C)
    closer.click(function () {
      Popup.setPosition(undefined)
      this.blur()
      return false
    })
  } else {
    Popup.setPosition(undefined)
  }
}

// 释放叠加层
function releaseOverlay() {
  if (_iMap != null) {
    const overlays = _iMap.getOverlays().array_
    let len = overlays.length
    while (len > 0) {
      len--
      _iMap.removeOverlay(overlays[len])
      overlays.splice(len, 1)
    }
    OverlayLayer = null
  }
}

// 更新overlay位置
function updateOverlayPosition(tagid, ncoords) {
  OverlayLayer = _iMap.getOverlayById(tagid)
  if (OverlayLayer != null) {
    if (OverlayLayer.getId() === tagid) {
      if (OverlayLayer.getPosition() != undefined) {
        OverlayLayer.setPosition(ncoords)
      }
    }
  }
}

/**
 * 加载鼠标工具tooltip
 */
function _createTooltip(t) {
  if (TooltipElement) {
    TooltipElement.parentNode.removeChild(TooltipElement)
  }
  TooltipElement = document.createElement('div')
  TooltipElement.className = 'maptooltip hidden'
  Tooltip = new Overlay({
    element: TooltipElement,
    offset: [10, 0],
    positioning: 'center-left'
  })
}

/**
 * 加载测量提示工具Measuretooltip
 */
function _createMeasureTooltip() {
  if (measureTooltipElement) {
    measureTooltipElement.parentNode.removeChild(measureTooltipElement)
  }
  measureTooltipElement = document.createElement('div')
  measureTooltipElement.className = 'maptooltip tooltip-static' // tooltip-measure & tooltip-static
  measureTooltip = new Overlay({
    element: measureTooltipElement,
    offset: [0, -15],
    positioning: 'bottom-center'
  })
  _iMap.addOverlay(measureTooltip)
}

/**
 *坐标（锚点、标签）转换成像素    （米－＞像素）
 */
function _TransPixel(c) {
  var PX
  $.each(c, function (i, item) {
    if (item == undefined || item.length == undefined) {
      var X = c[0] * _dPR
      var Y = _validate(c[1]) * _dPR
      PX = [X, Y]
    } else {
      $.each(c, function (i, item) {
        var j, jj
        for (j = 0, jj = item.length; j < jj; ++j) {
          item[j] = [item[j][0] * _dPR, _validate(item[j][1]) * _dPR]
        }
        PX = [item]
      })
    }
  })
  return PX
}

function _validate(num) // 判断正数
{
  var reg = /^\d+(?=\.{0,1}\d+$|$)/
  if (reg.test(num)) return -(num)
  return Math.abs(num)
}

/**
 *坐标（锚点、标签）转换成米    （像素－＞米）
 */
function _TransMetric(c, fix = 2) {
  var M
  $.each(c, function (i, item) {
    if (item.length == undefined) {
      var X = (c[0] / _dPR).toFixed(fix)
      var Y = _validate((c[1] / _dPR)).toFixed(fix)
      M = [X, Y]
    } else {
      $.each(c, function (i, item) {
        var j, jj
        for (j = 0, jj = item.length; j < jj; ++j) {
          item[j] = '[' + [(item[j][0] / _dPR).toFixed(fix), (_validate(item[j][1]) / _dPR).toFixed(fix)] + ']'
        }
        M = [item]
      })
    }
  })
  return M
}

// 屏幕坐标转换为实际坐标（Number类型）
function _TransMetric_Number(c, fix) {
  var M
  $.each(c, function (i, item) {
    if (item.length == undefined) {
      var X = (c[0] / _dPR).toFixed(fix)
      var Y = _validate((c[1] / _dPR)).toFixed(fix)
      M = [X, Y]
    } else {
      $.each(c, function (i, item) {
        var j, jj
        for (j = 0, jj = item.length; j < jj; ++j) {
          item[j] = [parseFloat((item[j][0] / _dPR).toFixed(fix)), parseFloat((_validate(item[j][1]) / _dPR).toFixed(fix))]
        }
        M = [item]
      })
    }
  })
  return M
}

/**
 * 输出标签位置点
 */
function _TransMetric_XY(c, fix) {
  var X = (c[0] / _dPR).toFixed(fix)
  var Y = (c[1] / _dPR).toFixed(fix) * -1
  var M = [X, Y]
  var M = 'X:' + X + '  ' + 'Y:' + Y
  return M
}
/** ***************************************************************************/

/** 判断是否IE浏览器*/
function isIE() {
  if (!!window.ActiveXObject || 'ActiveXObject' in window) {
    return true
  } else {
    return false
  }
}

/** 判断是否手机浏览*/
function isMobile() {
  var isMobile = {
    Android: function () {
      return !!navigator.userAgent.match(/Android/i)
    },
    BlackBerry: function () {
      return !!navigator.userAgent.match(/BlackBerry/i)
    },
    iOS: function () {
      return !!navigator.userAgent.match(/iPhone|iPad|iPod/i)
    },
    Windows: function () {
      return !!navigator.userAgent.match(/IEMobile/i)
    }
  }

  return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows())
}

export {
  Load_Map,
  Load_Tag,
  Load_Fence,
  Load_Camera,
  Load_Anchor,
  Load_Alertor,
  TagAjax,
  _TransPixel,
  TagStyle,
  _iMap,
  _dPR,
  OverlayLayer,
  FenceLayer,
  FenceSource,
  _createTooltip,
  _createMeasureTooltip,
  _TransMetric,
  _TransMetric_Number,
  Tooltip,
  TooltipElement,
  measureTooltipElement,
  measureTooltip,
  CameraLayer,
  CameraSource,
  AlertorSource,
  AlertorLayer,
  checkZoom,
  _PopupVideo,
  _Popup,
  releaseFence,
  clearFence,
  setMapCenter,
  releaseOverlay,
  updateOverlayPosition,
  LoadTypeData,
  getTypeData,
  loadLocalFence,
  deleteFence,
  sendThis,
  sendCameraPreview,
  flashAnimate,
  removeMap,
  Load_MapFence
}
